/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.security.*;
import java.util.*;
import javax.smartcardio.*;
import java.security.cert.CertificateException;


public class ObtenerDatos {

     public ObtenerDatos() throws Exception{

    }

     public String obtenerNombre() throws Exception {
        String name = LeerDatos();
        return name;
    }

    private String LeerDatos() throws Exception {


        String alias="";
        boolean found = false;
                
        Card c = ConexionTarjeta();
        if(c == null)
            throw new Exception("No se ha encontrado ninguna tarjeta");
       
        c.disconnect(true);

        try {
            
            String configName="";
            String osName = System.getProperty("os.name").toLowerCase();
                       
            if(osName.substring(0,7).compareTo("windows")==0)
                configName = "dnie_windows.cfg";//Estamos en un Sistema Windows
            else if(osName.substring(0,5).compareTo("linux")==0)
                    configName = "dnie_linux.cfg";//Estamos en un Sistema Linux
                else if(osName.substring(0,3).compareTo("mac")==0)
                        configName = "dnie_mac.cfg";//Estamos en un Sistema Mac

            Provider p = new sun.security.pkcs11.SunPKCS11(configName);
	    Security.addProvider(p);

	    //Obtenemos el fichero a firmar
            //Iniciamos el acceso a los certificados almacenados en la tarjeta.
            KeyStore keyStore = KeyStore.getInstance("PKCS11", "SunPKCS11-dnie");
            char[] pin = "pindeusuario".toCharArray();

            keyStore.load(null, pin);
            
            //Obtenemos la clave privada para realizar la firma del documento.
            Enumeration enumeration = keyStore.aliases();
            java.security.cert.Certificate certificado;

            do{
                alias = enumeration.nextElement().toString();
                if(alias.compareTo("CertFirmaDigital")==0)
                    found=true;
                else
                    found=false;

            }while(enumeration.hasMoreElements() && found==false);

            if(found==true)
            {
                certificado = keyStore.getCertificate(alias);
                Key key = keyStore.getKey(alias, pin);

                if (key instanceof PrivateKey) {

                    byte[] data, realSig;

                    //Firmamos los datos
                    Signature sig = Signature.getInstance("SHA1withRSA");
                    sig.initSign((PrivateKey)key);
                    data = new String("Datos a firmar").getBytes();

                    sig.update(data);
                    realSig = sig.sign();
                    
                }
            }
            
        } catch (CertificateException e) {
	      System.err.println("Caught exception " + e.toString() + ". Compruebe que no ha introducido un pin.");

        } catch (Exception e) {
	      System.err.println("Caught exception " + e.toString());
        }

        return alias;
    }

    
    private Card ConexionTarjeta() throws Exception {
        
        Card card = null;
        TerminalFactory factory = TerminalFactory.getDefault();
        List<CardTerminal> terminals = factory.terminals().list();
        //System.out.println("Terminals: " + terminals);

        for (int i = 0; i < terminals.size(); i++) {

            /*System.out.println("Getting terminal " + i + ": " + terminals.get(i).getName());
            System.out.println("Terminal name: " + terminals.get(i).getName());
            System.out.println("");*/

            // get terminal
            CardTerminal terminal = terminals.get(i);
            // establish a connection with the card
            //System.out.println("Trying connect card");

            try {
                if(terminal.isCardPresent()) {
                    card = terminal.connect("*"); //T=0, T=1 or T=CL(not needed)
                    /*System.out.println("Connected");
                    System.out.println("");*/

                }
		    } catch (Exception e) {

                System.out.println("Exception catched: " + e.getMessage());
                card = null;
		    }
        }
        return card;
    }

}

